import { Component, OnInit } from '@angular/core';
import { TodoService } from '../todo.service';
import { Todo } from '../todo.model';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-todo-list',
  templateUrl: './todo-list.component.html',
  styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent implements OnInit {

  status: '' | 'active' | 'completed' = '';

  constructor(
    public readonly todoService: TodoService,
    private readonly route: ActivatedRoute
  ) {
    this.route.paramMap
      .subscribe(params => {
        this.status = (params.get('status') as 'active' | 'completed') ?? '';
      });
  }

  ngOnInit(): void {
  }

  deleteTodo(todo: Todo): void {
    this.todoService.deleteTodo(todo);
  }

  stopEditing(todo: Todo, content: string): void {
    if(todo.editing) {
      if (content.trim().length > 0) {
        todo.content = content;
      } else {
        this.todoService.deleteTodo(todo);
      }
      todo.editing = false;
    }
  }

  cancelEditing(todo: Todo): void {
    todo.editing = false;
  }

  toggleComplete(checked: boolean, todo: Todo): void {
    this.todoService.toggleTodo(checked, todo);
  }

  toggleAllComplete(checked: boolean): void {
    this.todoService.toggleTodo(checked);
  }

  clearCompletedTodos(): void {
    this.todoService.clearCompletedTodos();
  }

}
